<%@ Page Language="VB" MasterPageFile="~/Default.master" Title="Forum Thread" Strict="false" %>


<%@ Import Namespace="ClubStarterKit.Data" %>
<%@ Register Src="ForumUser.ascx" TagName="ForumUser" TagPrefix="uc1" %>

<script runat="server">
    #Region "Diclaimer"
'Copyright (c) 2006, Mark Bracewell (bracewell at wgg dot com)
'All rights reserved.
'Redistribution and use in source and binary forms, with or without
'modification, are permitted provided that the following conditions are met: 
'*

'* Redistributions of source code must retain the above copyright
'notice, this list of conditions and the following disclaimer.
'* Redistributions in binary form must reproduce the above copyright
'notice, this list of conditions and the following disclaimer in the
'documentation and/or other materials provided with the distribution.
'* The name Mark Bracewell may not be used to endorse or promote products
'derived from this software without specific prior written permission. 
'* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
'DISCLAIMED. IN NO EVENT SHALL MARK BRACEWELL BE LIABLE FOR ANY
'DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
'(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
'LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
'ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
#End Region
    Private TopicID As String
    Dim bAdmin As Boolean
    Dim bAdminOnly As Boolean
    Dim bLocked As Boolean
    Dim bSticky As Boolean
    Dim bWatch As Boolean
    Dim bAnswered As Boolean
    Dim userGuid As Guid
    Dim bModerator As Boolean
    Dim threadid As Integer = 0
    
    Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
        If User.Identity.IsAuthenticated Then
            e.Command.Parameters("@pageSize").Value = ClubStarterKit.Web.Forum.GetCurrentForumUser().MsgsPerPage().ToString()
        End If
    End Sub
    
    Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)
        Dim pages As Integer
        pages = CInt(e.Command.Parameters("@pageCount").Value)
        pn1.Count = pages
        Pn2.Count = pages
    End Sub
        
    Protected Sub pn1_SelectedPageChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Pn2.SelectedPage = pn1.SelectedPage
    End Sub
    
    
    Protected Sub Pn2_SelectedPageChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        pn1.SelectedPage = Pn2.SelectedPage
    End Sub
    
    Private Function GetTopicID() As String
        Return TopicID
    End Function
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            threadid = CInt(Request("th"))
        Catch ex As Exception
            Response.Redirect("topics.aspx", True)
        End Try
        If threadid = 0 Then Response.Redirect("topics.aspx", True)
        Dim ti As ClubStarterKit.Data.ForumTopicInfo
        ti = ClubStarterKit.Web.Forum.GetTopicInfoByThread(threadid)
        
        bAdmin = User.IsInRole("Administrators")
        
        
        If User.Identity.IsAuthenticated Then
            userGuid = New Guid(Membership.GetUser.ProviderUserKey.ToString())
            If Membership.GetUser().ProviderUserKey() = ti.moderatorkey() Then
                bModerator = True
                AdminLinks.Visible = True
            Else
                bModerator = False
            End If
        Else
            bModerator = False
        End If
        
        TopicID = ti.topicid.ToString()
        bLocked = ClubStarterKit.Web.Forum.GetThreadLock(threadid)
        If Not IsPostBack Then
            bAdminOnly = ClubStarterKit.Web.Forum.IsAdminOnlyThread(threadid)
            LockButton.Text = CType(IIf(bLocked, "Unlock Thread", "Lock Thread"), String)
            UnlockImg.Visible = IIf(bLocked, True, False)
            LockImg.Visible = IIf(bLocked, False, True)
            bSticky = ClubStarterKit.Web.Forum.GetThreadSticky(threadid)
            StickyButton.Text = CType(IIf(bSticky, "Make Un-Sticky", "Make Sticky"), String)
            ThreadsCrumb.NavigateUrl = "Threads.aspx?to=" & ti.topicid.ToString()
            ThreadsCrumb.Text = ti.topic
            DropDownList1.Items.Add(New ListItem("Oldest First", "asc"))
            DropDownList1.Items.Add(New ListItem("Newest First", "desc"))
            If Page.User.Identity.IsAuthenticated Then
                DropDownList1.SelectedIndex = CInt(IIf(ClubStarterKit.Web.Forum.GetCurrentForumUser().SortDescending, 1, 0))
            End If
            NewThreadLink.NavigateUrl = "addpost.aspx?to=" & ti.topicid.ToString() & "&pa=0"
            NewThreadLink.ToolTip = "Add New Thread to " & ti.topic & " ..."
            newimg.Visible = True
            If Not bAdmin AndAlso Not bModerator Then
                If (ti.section = True Or ti.visible = False) Then
                    Response.Redirect("topics.aspx", True)
                End If
                If ti.locked Then
                    NewThreadLink.Enabled = False
                    NewThreadLink.ToolTip = "This Topic is Locked"
                    newimg.Visible = False
                End If
                AdminLinks.Visible = False
                If bAdminOnly = True Then
                    Response.Redirect("topics.aspx")
                End If
            End If
            If User.Identity.IsAuthenticated Then
                ClubStarterKit.Web.Forum.MarkThreadRead(threadid, userGuid)
                bWatch = ClubStarterKit.Web.Forum.GetThreadWatch(threadid, New Guid(Membership.GetUser.ProviderUserKey.ToString()))
                WatchButton.Text = CType(IIf(bWatch, "Stop Watching this Thread", "Watch this Thread"), String)
            Else
                WatchLink.Visible = False
            End If
            bAnswered = ClubStarterKit.Web.Forum.IsAnswered(threadid)
        End If
    End Sub
    
    Private Function CanReply() As Boolean
        Return bAdmin Or (Not bLocked)
    End Function
    
    Private Function CanEdit(ByVal messageid As Integer) As Boolean
        If IsSelf(messageid) = True Then
            Return True
        Else
            Return IsModerator()
        End If
    End Function
    
    Private Function IsAdmin() As Boolean
        Return bAdmin
    End Function
    
    Private Function IsModerator() As Boolean
        Return bModerator
    End Function
    
    Private Function IsAnswered() As Boolean
        Return bAnswered
    End Function
    
    Private Function AdminOnly() As Boolean
        Return bAdminOnly
    End Function

    Protected Sub DeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If bAdmin Then
            ClubStarterKit.Web.Forum.DeleteThread(threadid)
            Response.Redirect(ThreadsCrumb.NavigateUrl)
        End If
    End Sub

    Protected Sub LockButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If bAdmin Then
            bLocked = ClubStarterKit.Web.Forum.GetThreadLock(threadid)
            ClubStarterKit.Web.Forum.SetThreadLock(threadid, Not bLocked)

            LockButton.Text = CType(IIf(bLocked, "Lock Thread", "Unlock Thread"), String)
            UnlockImg.Visible = IIf(bLocked, False, True)
            LockImg.Visible = IIf(bLocked, True, False)
        End If

        SqlDataSource1.Select(New System.Web.UI.DataSourceSelectArguments())
        Repeater1.DataBind()
    End Sub
    
    Protected Sub StickyButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If bAdmin Then
            bSticky = ClubStarterKit.Web.Forum.GetThreadSticky(threadid)
            ClubStarterKit.Web.Forum.SetThreadSticky(threadid, Not bSticky)

            StickyButton.Text = CType(IIf(bSticky, "Make Sticky", "Make Un-Sticky"), String)
        End If
        SqlDataSource1.Select(New System.Web.UI.DataSourceSelectArguments())
        Repeater1.DataBind()
    End Sub
    
    Protected Sub WatchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        bWatch = ClubStarterKit.Web.Forum.GetThreadWatch(threadid, userGuid)
        ClubStarterKit.Web.Forum.SetThreadWatch(threadid, userGuid, Not bWatch)

        WatchButton.Text = CType(IIf(bWatch, "Watch this Thread", "Stop Watching this Thread"), String)
        SqlDataSource1.Select(New System.Web.UI.DataSourceSelectArguments())
        Repeater1.DataBind()
    End Sub
    
    Private Function GetSignature(ByVal memberid As Object) As String
        If Not User.Identity.IsAuthenticated Then
            Return ClubStarterKit.Web.Forum.GetCachedForumUser(memberid).Signature()
        End If
        If ClubStarterKit.Web.Forum.GetCurrentForumUser().ShowSignatures() Then
            Return ClubStarterKit.Web.Forum.GetCachedForumUser(memberid).Signature()
        End If
        Return ""
    End Function
    
    Private Function CurrentURL() As String
        Dim url As String = Request.Url.ToString()
        Return System.Web.HttpUtility.UrlEncode(url)
    End Function
    
    Private Function CanMarkAnswer(ByVal messageid As String) As Boolean
        If bLocked = False Then
            If User.Identity.IsAuthenticated Then
                If IsAnswered() = False Then
                    If IsSelf(messageid) = True Then
                        If ClubStarterKit.Web.Forum.IsFirstMessage(messageid) = True Then
                            Return True
                        Else
                            Return False
                        End If
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function
    
    Private Function CanUnmarkAnswer(ByVal Answer As Boolean, ByVal messageid As String) As Boolean       
        If bLocked = False Then
            If User.Identity.IsAuthenticated Then
                If Answer = True Then
                    If IsSelf(messageid) = True Then
                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function
    
    Private Function IsSelf(ByVal messageid As Integer) As Boolean
        Dim CurrentGUID As Guid = Membership.GetUser().ProviderUserKey()
        Dim OrigionalMessageGUID As Guid = ClubStarterKit.Web.Forum.GetMemGuidByMsg(messageid)
        
        If CurrentGUID = OrigionalMessageGUID Then
            Return True
        Else
            Return False
        End If
    End Function
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="body">
        <div class="fullwidth">
            <table cellspacing="0" cellpadding="0" width="100%">
                <tr>
                    <td style="height: 16px">
                        <asp:HyperLink ID="ForumsCrumb" NavigateUrl="Topics.aspx" runat="server">Forums</asp:HyperLink>
                        &raquo;
                        <asp:HyperLink ID="ThreadsCrumb" runat="server" />
                    </td>
                    <td align="right" style="height: 16px">
                        <span id="AdminLinks" runat="server">
                            <asp:Image ID="del" runat="server" SkinID="deletethread" Visible='<%# DeleteButton.Visible %>' /> <asp:LinkButton ID="DeleteButton" runat="server" OnClick="DeleteButton_Click">Delete Thread</asp:LinkButton>
                              
                            <asp:Image ID="UnlockImg" runat="server" SkinID="unlockthread" /><asp:Image ID="LockImg" runat="server" SkinID="lockthread" /> <asp:LinkButton ID="LockButton" runat="server" OnClick="LockButton_Click"></asp:LinkButton>
                              
                            <asp:Image ID="sticky" runat="server" SkinID="sticky" Visible='<%# StickyButton.Visible %>' /> <asp:LinkButton ID="StickyButton" runat="server" OnClick="StickyButton_Click"></asp:LinkButton>
                              </span>
                        <span id="WatchLink" runat="server">
                                 <asp:Image id="watchimg" runat="server" SkinID="watch" Visible='<%# WatchButton.Visible %>'/> <asp:LinkButton ID="WatchButton" runat="server" OnClick="WatchButton_Click"></asp:LinkButton>
                                  </span>
                         <asp:Image ID="newimg" runat="server" SkinID="newthread" /> <asp:HyperLink ID="NewThreadLink" runat="server">New Thread</asp:HyperLink>
                    </td>
                </tr>
            </table>
        </div>
        <div class="fullwidth">
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ClubSiteDB %>"
                SelectCommand="GetThreadPage" SelectCommandType="StoredProcedure" OnSelected="SqlDataSource1_Selected"
                DataSourceMode="DataSet" EnableViewState="true" OnSelecting="SqlDataSource1_Selecting">
                <SelectParameters>
                    <asp:QueryStringParameter Name="threadid" QueryStringField="th" Type="Int32" />
                    <asp:ControlParameter Name="pageNum" ControlID="pn1" PropertyName="SelectedPage" />
                    <asp:Parameter DefaultValue="10" Name="pageSize" Type="Int32" />
                    <asp:ControlParameter ControlID="DropDownList1" Name="sortDir" PropertyName="SelectedValue" />
                    <asp:Parameter Name="pageCount" Direction="ReturnValue" Type="Int32" />
                </SelectParameters>
            </asp:SqlDataSource>
            <div class="newscrumbs" style="float: left">
                <strong>Page</strong>:
                <Club:PageNumberer ID="pn1" runat="server" CssClass="PageNumbers" DisplayedPages="7"
                    OnSelectedPageChanged="pn1_SelectedPageChanged" />
            </div>
            <div style="float: right">
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
                </asp:DropDownList>
            </div>
            <div class="dashedline">
            </div>
            <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" EnableViewState="true">
                <HeaderTemplate>
                    <table width="100%" cellpadding="0" cellspacing="0">
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <td class="thread" align="center" valign="top" width="130">
                            <uc1:ForumUser MemberID='<%# Eval("memberid") %>' ID="ForumUser1" runat="server" />
                        </td>
                        <td colspan="2" class="thread" valign="top">
                            <h3>
                                <asp:Label ID="Labelsubject" runat="server" Text='<%# Eval("subject") %>'></asp:Label></h3>
                            <asp:Label ID="Labelpostdate" runat="server" Text='<%# Eval("postdate") %>'></asp:Label>
                            
                                                      
                            <div class="msgbody">
                                <asp:Label ID="Labelbody" runat="server" Text='<%# Eval("body") %>'></asp:Label>
                                <div style="padding-top:5px">
                                <asp:Label ID="LabelSig" runat="server" Text='<%# GetSignature(Eval("memberid")) %>'></asp:Label>
                                </div>
                                <div style="text-align:center"><asp:Image ID="answerimg" runat="server" SkinID="answer" Visible='<%# Eval("answer") %>'/> <asp:Label ID="AnswerLBL" runat="server" Text="ANSWER" Visible='<%# Eval("answer") %>' Font-Bold="true" Font-Size="Large" /></div>
                                </div>
                        </td>
                    </tr>
                    <tr>
                        <td class="threadcontrols">
                            &nbsp;</td>
                        <td class="threadcontrols">
                            <asp:Image ID="edtimg" runat="server" SkinID="editthread" /> <asp:HyperLink ID="EditLink" Visible='<%# CanEdit(Integer.Parse(Eval("id"))) %>' NavigateUrl='<%# "EditPost.aspx?ms=" & Eval("id").ToString() %>'
                                runat="server">Edit</asp:HyperLink>
                            &nbsp;
                        </td>
                        <td align="right" class="threadcontrols">
                            &nbsp;<span visible='<%# CanReply() %>' id="Panel1" runat="server">
                                <asp:Image ID="ReplyIMG" runat="server" SkinID="reply" /> <asp:HyperLink ID="HyperLink1" NavigateUrl='<%# "addpost.aspx?to=" & GetTopicID & "&pa=" & Eval("id").ToString() %>'
                                    runat="server">Reply</asp:HyperLink>
                                 
                                <asp:Image ID="QuoteReplyImg" runat="server" SkinID="quotedreply" /> <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# "addpost.aspx?qu=1&to=" & GetTopicID & "&pa=" & Eval("id").ToString() %>'>Quoted Reply</asp:HyperLink> 
                                <asp:Image ID="ReportIMG" runat="server" SkinID="spam" /> <asp:HyperLink ID="ReportMsg" runat="server" NavigateUrl='<%# "report.aspx?messageid=" & Eval("id").ToString() & "&ReturnURL=" & CurrentURL %>' Text="Report" /> 
                            </span>
                            <span visible='<%# CanMarkAnswer(Eval("id").ToString()) %>' id="answer" runat="server">
                              <asp:Image ID="Image1" runat="server" SkinID="markasanswer" /> <asp:HyperLink ID="MarkAnswer" runat="server" Text="Mark as Answer" NavigateUrl='<%# "EditPost.aspx?markreadmessageid=" & Eval("id").ToString() & "&ReturnURL=" & CurrentURL() %>' />
                            </span>
                            <span visible='<%# CanUnmarkAnswer(Eval("answer"), Eval("id").ToString()) %>' id="unanswer" runat="server">
                              <asp:Image ID="unmarkanswerimg" runat="server" SkinID="markasanswer" /> <asp:HyperLink ID="UnmarkAnswer" runat="server" Text="Unmark as Answer" NavigateUrl='<%# "EditPost.aspx?unmarkreadmessageid=" & Eval("id").ToString() & "&ReturnURL=" & CurrentURL() %>' />
                            </span>
                        </td>
                    </tr>
                </ItemTemplate>
                <SeparatorTemplate>
                </SeparatorTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
            <div class="dashedline">
            </div>
            <div class="newscrumbs">
                <strong>Page</strong>:
                <Club:PageNumberer ID="Pn2" runat="server" DisplayedPages="7" CssClass="PageNumbers"
                    OnSelectedPageChanged="Pn2_SelectedPageChanged" />
                    
            </div>
        </div>
    </div>
</asp:Content>
